#!/usr/bin/php
<?php

$localDir = "/home/rsigler/sync";
$fd = inotify_init();

// IN_Q_OVERFLOW

/* To use:
 * IN_CLOSE_WRITE
 * IN_DELETE
 */
$watch_descriptor = inotify_add_watch($fd, $localDir, IN_ALL_EVENTS);

$fileMoved = array();
$dirMoved = array();
while (true) {
	$events = inotify_read($fd);
	foreach ($events as $event => $details) {
		$directory = false;
		//print ("$event => $details\n");
		print ("Event fired!\n\t");
		// print ("\t$key => $value\n");
		print ("File ({$details["name"]}) cookie ({$details["cookie"]}): ");
		switch ($details["mask"]) {
			case IN_CLOSE_WRITE:
				print "In Close Write\n";
				break;
			case IN_MODIFY:
				print "In Modify\n";
				break;
			case IN_ATTRIB:
				print ("In Attrib\n");
				break;
			case IN_MOVE:
				print ("In Move\n");
				break;
			case IN_CREATE:
				print ("In Create\n");
				break;
			case IN_DELETE:
				print ("In Delete\n");
				break;
			case IN_DELETE_SELF:
				print ("In Delete Self\n");
				break;
			case IN_MOVE_SELF:
				print ("In Move Self\n");
				break;
			case IN_MOVED_TO:
				print ("In Moved To\n");
				$fileMoved[$details["cookie"]]["to"] = $details["name"];
				break;
			case IN_MOVED_FROM:
				print ("In Moved From\n");
				$fileMoved[$details["cookie"]]["from"] = $details["name"];
				break;
			case IN_ISDIR | IN_CREATE:
				print ("Directory created\n");
				$watch_descriptor = inotify_add_watch($fd, "$localDir/{$details["name"]}", IN_ALL_EVENTS);
				break;
			case IN_ISDIR | IN_DELETE:
				print ("Directory deleted\n");
				break;
			case IN_ISDIR | IN_MOVED_FROM:
				$dirMoved[$details["cookie"]]["from"] = $details["name"];
				break;
			case IN_ISDIR | IN_MOVED_TO:
				$dirMoved[$details["cookie"]]["to"] = $details["name"];
				break;
			
			default:
				printf ("Other Unknown Mask (0x%x)\n", $details["mask"]);
				break;
		}
		
		// Detect a file move
		if (isset($fileMoved[$details["cookie"]])) {
			print "File move detected...\n";
			if (isset($fileMoved[$details["cookie"]]["from"])) {
				print "Got a move from...\n";
			}
			if (isset($fileMoved[$details["cookie"]]["to"])) {
				print "Got a move to...\n";
			}
			if (isset($fileMoved[$details["cookie"]]["from"]) && (isset($fileMoved[$details["cookie"]]["to"]))) {
				print ("Got a full move transaction. A file has been renamed...\n");
			}
		}
		
		// Detect directoy move
		if (isset($dirMoved[$details["cookie"]])) {
			print "Directory move detected...\n";
			if (isset($dirMoved[$details["cookie"]]["from"])) {
				print "Got a move from...\n";
			}
			if (isset($dirMoved[$details["cookie"]]["to"])) {
				print "Got a move to...\n";
			}
			if (isset($dirMoved[$details["cookie"]]["from"]) && (isset($dirMoved[$details["cookie"]]["to"]))) {
				print ("Got a full move transaction. A Directory has been renamed...\n");
			}
		}

	}
}
?>
